#include<stdio.h>
#include<unistd.h>
#include<pthread.h>
pthread_cond_t cond1;
pthread_cond_t cond2;
pthread_mutex_t mutex;
int count=0;

void* routeA(void*arg)
{
  while(1)
  {
    pthread_mutex_lock(&mutex);
    while(count<=0)
    {
      pthread_cond_wait(&cond1,&mutex);
    }
    printf("I am process A\n");
    count--;
    pthread_cond_signal(&cond2);
    pthread_mutex_unlock(&mutex);
    sleep(1);
  }
  return NULL;
}
void* routeB(void*arg)
{
  while(1)
  {
    pthread_mutex_lock(&mutex);
    while(count>0)
    {
      pthread_cond_wait(&cond2,&mutex);
    }
    printf("I am process B\n");
    count++;
    pthread_cond_signal(&cond1);
    pthread_mutex_unlock(&mutex);
    sleep(1);
  }
  return NULL;
}
int main()
{
  pthread_t tid1,tid2;
  pthread_mutex_init(&mutex,NULL);
  pthread_cond_init(&cond1,NULL);
  pthread_cond_init(&cond2,NULL);
  int ret;
  ret=pthread_create(&tid1,NULL,routeA,NULL);
  if(ret!=0)
  {
    printf("pthread_create error\n");
    return -1;
  }
  ret=pthread_create(&tid2,NULL,routeB,NULL);
  if(ret!=0)
  {
    printf("pthread_create error\n");
    return -1;
  }

  pthread_join(tid1,NULL);
  pthread_join(tid2,NULL);
  pthread_mutex_destroy(&mutex);
  pthread_cond_destroy(&cond1);
  pthread_cond_destroy(&cond2);
  return 0;
}
